package helperx

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
)

// AesGcmDecrypt AES-256-GCM 解密
func AesGcmDecrypt(secret, nonceStr, key, addData string, raw bool) (string, error) {
	cryptByte := []byte(secret)
	if true != raw {
		cryptByte, _ = base64.StdEncoding.DecodeString(secret)
	}
	nonce := []byte(nonceStr)

	// 检查
	if secret == "" {
		return "", errors.New("empty secret")
	}
	if !validKey(key) {
		return "", errors.New("invalid key size")
	}

	// 分组秘钥
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return "", err
	}

	// 加密模式
	blockMode, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}
	plaintext, err := blockMode.Open(nil, nonce, cryptByte, []byte(addData))
	if err != nil {
		return "", err
	}

	return string(plaintext), nil
}
